<template>
  <!-- 厂商建档 -->
  <div class="vendorDoc">
    <div class="mask" :style="{ display: showMask }"></div>
    <new-data
      class="newdata"
      :style="{ display: newShow }"
      @closeClick="closeClick"
      @saveInfo="saveInfo"
      @addDataLen="
        () => {
          this.dataLen++
        }
      "
      :detailInfo="details"
      :showType="showType"
    >
    </new-data>

    <show-detail
      class="details"
      :style="{ display: detailsShow }"
      @closeClick="detailClose"
      :detailInfo="details"
    >
    </show-detail>

    <!-- 操作 -->
    <div class="operation">
      <el-button type="primary" icon="el-icon-plus" @click="newClick"
        >新建</el-button
      >
      <el-button
        style="z-index: 2"
        icon="el-icon-edit-outline"
        @click="editClick"
        >编辑</el-button
      >
      <!-- <el-button @change="postEx" icon="el-icon-download">导入</el-button> -->
      <div class="dr">
        <i class="el-icon-download"></i>
        导入
        <input
          ref="upload"
          accept=".xls, .xlsx"
          class="outputlist_upload"
          type="file"
        />
      </div>
      <el-button @click="EXpe" icon="el-icon-upload2">导出</el-button>
      <el-button @click="dele" icon="el-icon-delete">删除</el-button>
    </div>

    <!-- 表 -->
    <!-- <div class="venContent">   max-height="680" -->
    <el-table
      :data="vendorData"
      style="width: 100%"
      id="outTable"
      highlight-current-row
      :header-cell-style="{ background: '#f4f4f4', padding: 0, height: '40px' }"
      :cell-style="{ padding: 0, height: '36px' }"
      @row-dblclick="dbClick"
      @row-click="rowClick"
      height="82vh"
    >
      <el-table-column
        prop="no"
        label="厂商编号"
        width="100"
        sortable
        v-if="selectHeaderList.indexOf('厂商编号') != -1"
      >
      </el-table-column>
      <el-table-column
        prop="name"
        label="厂商简称"
        width="100"
        sortable
        v-if="selectHeaderList.indexOf('厂商简称') != -1"
      >
      </el-table-column>
      <el-table-column
        prop="brandedCompany"
        label="品牌公司"
        width="100"
        v-if="selectHeaderList.indexOf('品牌公司') != -1"
      >
      </el-table-column>
      <el-table-column
        prop="contact"
        label="联系人"
        width="80"
        v-if="selectHeaderList.indexOf('联系人') != -1"
      >
      </el-table-column>
      <el-table-column
        prop="principal"
        label="负责人"
        width="80"
        v-if="selectHeaderList.indexOf('负责人') != -1"
      >
      </el-table-column>
      <el-table-column
        prop="discount"
        label="折数"
        width="50"
        v-if="selectHeaderList.indexOf('折数') != -1"
      >
      </el-table-column>
      <el-table-column
        prop="phone"
        label="电话"
        width="150"
        v-if="selectHeaderList.indexOf('电话') != -1"
      >
      </el-table-column>
      <el-table-column
        prop="fax"
        label="传真"
        width="150"
        v-if="selectHeaderList.indexOf('传真') != -1"
      >
      </el-table-column>
      <el-table-column
        prop="nameAll"
        label="厂商"
        width="160"
        v-if="selectHeaderList.indexOf('厂商') != -1"
      >
      </el-table-column>
      <el-table-column
        prop="address"
        label="地址"
        width="450"
        v-if="selectHeaderList.indexOf('地址') != -1"
      >
      </el-table-column>
      <el-table-column
        prop="remark"
        label="备注"
        width="180"
        v-if="selectHeaderList.indexOf('备注') != -1"
      >
      </el-table-column>
      <el-table-column
        prop="curencyType"
        label="币种"
        width="50"
        v-if="selectHeaderList.indexOf('币种') != -1"
      >
      </el-table-column>
      <el-table-column
        prop="operation"
        label="操作"
        v-if="selectHeaderList.indexOf('操作') != -1"
      >
        <template slot-scope="scope">
          <p
            @click="showDetails(scope.$index, vendorData)"
            style="color: #017aff; cursor: pointer"
          >
            详情
          </p>
        </template>
      </el-table-column>
    </el-table>
    <!-- </div> -->

    <foot-view
      class="footView"
      :pagesNum="pagesNum"
      :hasPagination="true"
      :pageSize="limit"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    >
      <div slot="text">
        <el-popover
          placement="top-start"
          width="120"
          max-height="100px"
          trigger="click"
        >
          <el-checkbox-group v-model="selectHeaderList">
            <el-checkbox
              v-for="i in headerList"
              :label="i.value"
              :key="i.value"
              style="margin-bottom: 7px"
            ></el-checkbox>
          </el-checkbox-group>
          <i slot="reference" class="el-icon-date"> 表头配置</i>
        </el-popover>
        <span>数据库：{{ jxQuarter }}</span>
      </div>
    </foot-view>
  </div>
</template>

<script>
import {
  getManufacturer,
  deleteManufacturer,
  postExcel
} from '../../../network/manufacturer'

import newData from './childComps/NewData'
import showDetail from './childComps/ShowDetail'
import footView from '../../../components/FootView'
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
import outexp from '../../../components/mixins/outexp'
import enterUp from '../../../components/mixins/enterUp'
export default {
  name: 'vendorDoc',
  mixins: [outexp, enterUp],
  data() {
    return {
      JList: [],
      // outputs: [],//导入
      // isChange: false,
      showType: '新建',
      showMask: 'none',
      newShow: 'none',
      detailsShow: 'none',
      id: '',
      // 总数据条数
      dataLen: 0,
      // 总页码
      pagesNum: 0,
      // 分页条数
      limit: 20,
      // 当前页码
      currentPage: 1,
      vendorData: [],
      details: {},
      selectHeaderList: [
        '厂商编号',
        '厂商简称',
        '品牌公司',
        '联系人',
        '负责人',
        '折数',
        '电话',
        '传真',
        '厂商',
        '地址',
        '备注',
        '币种',
        '操作'
      ],
      headerList: [
        { value: '厂商编号' },
        { value: '厂商简称' },
        { value: '品牌公司' },
        { value: '联系人' },
        { value: '负责人' },
        { value: '折数' },
        { value: '电话' },
        { value: '传真' },
        { value: '厂商' },
        { value: '地址' },
        { value: '备注' },
        { value: '币种' },
        { value: '操作' }
      ],
      jxQuarter: null
      // jxQuarter: document.cookie.match(RegExp('jxQuarter' + '=([^;]+)'))[1]
    }
  },
  watch: {
    dataLen(a, b) {
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
    }
  },
  mounted() {
    this.$refs.upload.addEventListener('change', (e) => {
      //绑定监听表格导入事件
      this.readExcel(e)
    })
  },
  components: {
    newData,
    showDetail,
    footView
  },
  methods: {
    EXpe() {
      getManufacturer().then((res) => {
        console.log(res.data)
        if (res.data.code == 200) {
          this.vendorData = res.data.data
          this.$nextTick(() => {
            this.exp()
          })
          this.saveInfo()
        }
      })
    },
    saveInfo() {
      let params = {
        limit: this.limit,
        page: 1
      }
      this._getManufacturer(params)
    },
    newClick() {
      this.showType = '新建'
      this.details = {}
      this.newShow = 'block'
      this.showMask = 'block'
    },
    closeClick() {
      this.newShow = 'none'
      this.showMask = 'none'
    },
    showDetails(index, data) {
      this.showType = '详情'
      this.details = data[index]
      this.newShow = 'block'
      this.showMask = 'block'
      // console.log(this.details)
      // console.log(this.showType)
    },
    detailClose() {
      this.newShow = 'none'
      this.showMask = 'none'
      // @detailClose="detailClose"
    },
    dbClick(e) {
      // console.log(e)
      this.showType = '编辑'
      // this.details = e
      this.newShow = 'block'
      this.showMask = 'block'
    },
    rowClick(e) {
      // console.log(e)
      this.details = e
      this.id = e.id
    },
    editClick() {
      this.showType = '编辑'
      this.newShow = 'block'
      this.showMask = 'block'
    },

    readExcel(e) {
      //表格导入
      var that = this
      const files = e.target.files
      console.log(files)
      if (files.length <= 0) {
        //如果没有文件名
        return false
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$Message.error('上传格式不正确，请上传xls或者xlsx格式')
        return false
      }

      const fileReader = new FileReader()
      fileReader.onload = (ev) => {
        try {
          const edata = ev.target.result
          console.log(edata)
          const workbook = XLSX.read(edata, {
            type: 'binary'
          })

          const wsname = workbook.SheetNames[0] //取第一张表
          console.log(wsname)
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) //生成json表格内容
          console.log(ws)
          for (var a = 0; a < ws.length; a++) {
            this.JList.push(JSON.stringify(ws[a]))
          }
          console.log(this.JList)
          // let obj = {paramsList:ac,fieldMap:{brandedCompany:"123456"}}
          let obj = { paramsList: this.JList }
          console.log({ obj })

          postExcel(obj).then((res) => {
            console.log(res.data)
            if (res.data.code == 200) {
              this.$message({
                type: 'success',
                message: '导入成功!'
              })
              this._getManufacturer({
                limit: this.limit,
                page: this.currentPage
              })
            } else {
              this.$message({
                type: 'info',
                message: '导入失败，厂商编号不能重复'
              })
            }
          })

          this._getManufacturer({
            limit: this.limit,
            page: this.currentPage
          })

          that.outputs = [] //清空接收数据
          //编辑数据
          for (var i = 0; i < ws.length; i++) {
            var sheetData = {
              address: ws[i].addr,
              value: ws[i].value
            }
            that.outputs.push(sheetData)
          }
          this.$refs.upload.value = ''
        } catch (e) {
          return false
        }
      }
      fileReader.readAsBinaryString(files[0])
    },

    // 每页显示页数改变
    handleSizeChange(val) {
      this.limit = val
      // 总页码赋值
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
      let params = {
        limit: this.limit,
        page: this.currentPage
      }
      this._getManufacturer(params)
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      let params = {
        limit: this.limit,
        page: val
      }
      this._getManufacturer(params)
    },
    _getManufacturer(params = { limit: 99999 }) {
      getManufacturer(params).then((res) => {
        // console.log(res)
        this.vendorData = res.data.data
        this.id = ''
        // if (this.vendorData.length == 0 && this.currentPage > 1) {
        //   this.currentPage--
        //   this._getArtNo({limit: this.limit,page: this.currentPage})
        // }
      })
    },
    dele() {
      if (this.id == '') {
        this.$message({
          message: '请选择要删除的数据',
          type: 'warning',
          offset: 400
        })
        return
      }

      this.$confirm('此操作将永久删除本条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteManufacturer({ id: this.id }).then((res) => {
          // console.log(res.data)
          if (res.data.code == 200) {
            this.dataLen--
            this._getManufacturer({
              limit: this.limit,
              page: this.currentPage
            })
            this.$message({
              type: 'success',
              offset: 400,
              message: '删除成功!'
            })
          }
        })
      })
    }
  },

  created() {
    let jxQuarterVal = document.cookie.match(RegExp('jxQuarter' + '=([^;]+)'))
    this.jxQuarter = jxQuarterVal ? jxQuarterVal[1] : null
    
    this.inpList = this.getInput()
    // 网络请求
    this._getManufacturer({ limit: this.limit, page: this.currentPage })
    // 总条数，页码赋值
    getManufacturer().then((res) => {
      // console.log(res.data.data.length)
      this.dataLen = res.data.total
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
    })
  }
}
</script>

<style scoped>
.mask {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  opacity: 0.3;
  z-index: 9;
}
.newdata {
  z-index: 99;
}
.details {
  z-index: 99;
}
.vendorDoc {
  margin-right: 15px;
  padding: 0 15px;
  height: 95vh;
  background-color: white;
  position: relative;
}

/* 操作 */
.vendorDoc .operation {
  padding: 15px 0;
  white-space: nowrap;
  display: flex;
}
.vendorDoc .el-button {
  margin: 0 10px 0 0;
}
.vendorDoc .el-button span {
  font-size: 15px;
}

.vendorDoc .footView span {
  float: left;
  margin-right: 20px;
  line-height: 6vh;
  font-size: 14px;
}
.vendorDoc .footView span i {
  margin-right: 5px;
}
</style>
